import 'dart:developer';

import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class IntroductionSettingPageLogic extends ChangeNotifier {
  late final TextEditingController controller;
  late final FocusNode focusNode;

  void init() {
    controller = TextEditingController();
    focusNode = FocusNode();

    controller.text = AccountInfo.shared.userProfile?.introduction ?? '';
    controller.addListener(() {
      notifyListeners();
    });
  }

  Future<bool> updateIntroduction(String newIntroduction) async {
    if (newIntroduction == AccountInfo.shared.userProfile?.introduction) {
      return true;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );

      final response = await DataFetcher.shared.userApi.updateUserIntroduction(
        newIntroduction,
      );

      if (response.code == 0 && response.result?.field == 'introduction') {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        AccountInfo.shared.updateIntroduction(response.result!.value);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }
}
